import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:jetour_line/base_widget/base_image.dart';
import 'package:jetour_line/models/jetour_line_detail.dart';
import 'package:jetour_line/my_colors.dart';
import 'package:jetour_line/utils/extension_int.dart';
import 'image_network_widget.dart';

typedef SelIndexCallBack = Function(int index);
typedef ChangeIndexCallBack = Function(int index);

class BannerWidget extends StatefulWidget {
  final int _maxPage = 2000000000;

  /// 轮播切换间隔秒数.
  final int seconds;

  /// 是否自动播放
  final bool autoPlayer;
  final double width;
  final double height;
  final double radius;
  final List imagesList;
  final SelIndexCallBack? selIndexCallBack;
  final ChangeIndexCallBack? changeIndexCallBack;

  // const BannerWidget({Key? key}) : super(key: key);
  BannerWidget(
      this.imagesList, {
        Key? key,
        this.autoPlayer = true,
        this.seconds = 3,
        this.width = double.infinity,
        this.height = double.infinity,
        this.changeIndexCallBack,
        this.radius = 0.0,
        this.selIndexCallBack,
      })  : assert(imagesList.isNotEmpty),
        assert(seconds > 2),
        super(key: key);

  @override
  State<BannerWidget> createState() => _BannerWidgetState();
}

class _BannerWidgetState extends State<BannerWidget> {
  late PageController _pageController;
  Timer? _timer;

  var _currIndex = 0;
  int lastIndex  =  2000000000;
  @override
  void initState() {
    super.initState();
    if (widget.autoPlayer) {
      startTimeout();
    }
    _pageController = PageController(initialPage: widget._maxPage);
  }

  @override
  void dispose() {
    super.dispose();
    _pageController.dispose();
    if (_timer != null) {
      _timer!.cancel();
    }
  }

  void startTimeout() {
    _timer = Timer.periodic(const Duration(seconds: 3), (timer) {
      var tempIndex = _currIndex + 1;
      if (tempIndex >= widget.imagesList.length) {
        tempIndex = 0;
      }
      _timer ??= timer;
      _currIndex = tempIndex;

      if(widget.changeIndexCallBack != null){
        widget.changeIndexCallBack!(_currIndex);
      }
      setState(() {});
    });
  }

  List<Widget> getBottomIcon() {
    var forLength = widget.imagesList.length;
    var res = <Widget>[];
    for (var i = 0; i < forLength; i++) {
      if (_currIndex == i) {
        res.add(GestureDetector(
          /// 选中时的图标,可以更换为图片.
          child: Padding(
            padding: EdgeInsets.only(left: 10.px, right: 10.px),
            child: ClipRRect(
              borderRadius: BorderRadius.all(Radius.circular(7.px)),
              child: Container(
                width: 40.px,
                height: 14.px,
                color: MyColors.white,
              ),
            ),
          ),
          onTap: () {
            setState(() {
              _currIndex = i;
            });
          },
        ));
      } else {
        res.add(GestureDetector(
          /// 未选中时的图标,可以更换为图片.
          child: Padding(
            padding: EdgeInsets.only(left: 10.px, right: 10.px),
            child: ClipRRect(
              borderRadius: BorderRadius.all(Radius.circular(7.px)),
              child: Container(
                width: 14.px,
                height: 14.px,
                color: MyColors.appColor,
              ),
            ),
          ),
          onTap: () {
            setState(() {
              _currIndex = i;
            });
          },
        ));
      }
    }
    return res;
  }


  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: widget.width,
      height: widget.height,
      child: Stack(
        children: [
          PageView.builder(
              controller: _pageController,
              onPageChanged: (int index) {
                if(lastIndex<index){
                  _currIndex = _currIndex+1;
                }else{
                  _currIndex = _currIndex-1;
                }
                if (_currIndex >= widget.imagesList.length) {
                  _currIndex = 0;
                }if(_currIndex<0){
                  _currIndex = widget.imagesList.length-1;
                }
                lastIndex = index;
                setState(() {
                  if (_timer != null) {
                    _timer!.cancel();
                    _timer = null;
                    startTimeout();
                  }
                });
                if(widget.changeIndexCallBack!= null){
                  widget.changeIndexCallBack!(_currIndex);
                }
              },
              itemBuilder: (BuildContext context, int index) {
                return childWidget(index);
              }),
          Positioned(
              left: 2.0,
              right: 2.0,
              bottom: 10.0,
              child: Container(
                /// padding: EdgeInsets.all(5.0),
                  child: widget.imagesList.length > 10
                      ? SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: getBottomIcon(),
                    ),
                  )
                      : Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: getBottomIcon(),
                  )))
        ],
      ),
    );
  }

  Widget childWidget(int index) {
    var width = MediaQuery.of(context).size.width;
    var renderIndex = _currIndex - widget._maxPage;
    renderIndex = renderIndex % widget.imagesList.length;
    if (renderIndex < 0) {
      renderIndex += widget.imagesList.length;
    }

    bool isVideo = false;
    Videos videos;
    String img = '';
    if (widget.imagesList[_currIndex].runtimeType == String) {
      isVideo = false;
      img = widget.imagesList[_currIndex];
    } else if (widget.imagesList[_currIndex].runtimeType == Videos) {
      isVideo = true;
      videos = widget.imagesList[_currIndex];
      img = videos.frame;
    }
    return GestureDetector(
      onTap: () {
        if (widget.selIndexCallBack != null) {
          widget.selIndexCallBack!(_currIndex);
        }
      },
      child: Container(
          child: Stack(children: <Widget>[
            img.startsWith("https://") || img.startsWith("http://")
                ? ImageNetworkWidget(
              img,
              fit: BoxFit.cover,
              width: width,
              radius: widget.radius,
              // placeholder: (context, url) =>
              //     CircularProgressIndicator(),
              // errorWidget: (context, url, error) => Icon(Icons.error),
            )
                : FadeInImage(
              image: AssetImage(widget.imagesList[_currIndex]),
              placeholder: AssetImage("assets/images/loading.gif"),
              fit: BoxFit.cover,
              width: width,
              height: double.infinity,
            ),
            if(isVideo)
              Center(child: BaseImage(image: 'icon_gcvideo',width: 80.px,height: 80.px,),)

          ])),
    );
  }
}
